<!DOCTYPE html>
<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>首页</title>
  <link href="../style.css" rel="stylesheet" />
  <link rel="stylesheet" href="../vendor/element/index.css">
  <link rel="icon" href="../favicon.ico">
</head>

<body>
  <div class="app" id="app" v-cloak>
    <div id="index" class="bg-image" :style="{backgroundImage: `url(${picture})`}"></div>
    <div class="header">
      <el-button @click="logOut">退出登录</el-button>
      <el-button @click="openDialog">更换背景</el-button>
      <el-button @click="window.location.href = 'signIn.html'">立即注册</el-button>
    </div>
    <h2 class="title"></h2>
    <!--表单-->
    <div class="form-box">
      <el-form class="form" :model="form" ref="form" :rules="rules" label-position="left">

        <div class="btn-line" v-for="(item,index) in formItems" :class="item.class">
          <el-form-item   :label="item.label" :prop="item.prop">
            <el-input :id="copy+item.code" v-model="form[item.prop]" clearable></el-input>
          </el-form-item>
          <el-button class="cancel-btn" @click="submit(item.code)" round>生成</el-button>

          <div class="tag" v-if="item.code == 5">
            <div class="arrow">
              数组结构
              <div class="test">
                <div v-for="(o,index) in list" :key="index" class="text item">
                  <span>{{ `${index + 1}、` }}</span>
                  {{ o.value }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <!--更换背景对话框-->
    <el-dialog  class="form-dialog-box" width="500px" title="更换背景" :visible.sync="visible" v-if="visible">
      <el-form ref="dialogForm" :model="dialogForm" :rules="dialogRules" label-width="100px">
        <el-form-item  label="背景图片" prop="picture">

          <div class="upload-image">
            <el-upload
                    :style="{width:`${width}px`,height:`${height}px`}"
                    class="upload-image-box"
                    :headers="header"
                    :action="uploadAction"
                    :on-success="handleUploadSuccess"
                    :on-progress="handleUploadProgress"
                    :on-error="handleUploadError"
                    :before-upload="handleBeforeUpload"
                    :show-file-list="false"
            >
              <i v-show="!imageUrl" class="el-icon-plus"></i>
              <el-tooltip v-if="imageUrl" class="item" effect="dark" content="点击图片重新上传" placement="right">
                <img v-show="imageUrl" :src="imageUrl" class="image-preview"/>
              </el-tooltip>
            </el-upload>

            <el-progress class="upload-progress"
                         v-if="progessCount > 0 && progessCount < 100"
                         :style="{width:`${width + 2}px`,height:`${height + 2}px`}"
                         type="circle"
                         :percentage="progessCount"/>
          </div>

        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="dialogSubmit">提交</el-button>
        <el-button type="info" @click="visible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
  <!--vue-->
  <script src="../vendor/vue/vue.min.js"></script>
  <!--element-->
  <script src="../vendor/element/index.js"></script>
  <!--引入axios-->
  <script src="../vendor/axios/axios.min.js"></script>
  <script src="../app.js" lang="javascript"></script>
<script>
  // 构建Vue实例
  let vm = new Vue({
    el: '#app',
    data: {
      form: {
        name0: '', //
        name1: '', //
      },
      formItems:[
        {code:4,label: '1-5个字难改名字苹果',prop:'name4',},
        {code:1,label: '2-5个字换字难改苹果',prop:'name1',},
        {code:7,label: '苹果贵族居中',prop:'name7',},
        {code:2,label: '2-5个字难改换字安卓',prop:'name2',},
        {code:3,label: '1-5个字难改名字安卓',prop:'name3',},
        {code:6,label: '安卓贵族居中',prop:'name6',},
        {code:5,label: '6个字名字(这个会返回一个数组结构)',prop:'name5',class:'pos'},
        {code:8,label: '空白名',prop:'name8',},
        {code:9,label: '1-6重复名',prop:'name9',},
        {code:10,label: '1-10位英文名,可包含数字',prop:'name10',},

      ],
      rules:{
        name1:[{required:true,message: '不能为空',trigger: ['blur']},{min:2,max:5,message: '输入2-5个六个字符',trigger: ['blur','change']}],
        name2:[{required:true,message: '不能为空',trigger: ['blur']},{min:2,max:5,message: '输入2-5个六个字符',trigger: ['blur','change']}],
        name3:[{required:true,message: '不能为空',trigger: ['blur']},{max:5,message: '输入1-5个六个字符',trigger: ['blur','change']}],
        name4:[{required:true,message: '不能为空',trigger: ['blur']},{max:5,message: '输入1-5个六个字符',trigger: ['blur','change']}],
        name5:[{required:true,message: '不能为空',trigger: ['blur']}],
        name9:[{required:true,message: '不能为空',trigger: ['blur']},{max:6,message: '输入1-6个六个字符',trigger: ['blur','change']}],
        name10:[{required:true,message: '不能为空',trigger: ['blur']},{pattern:/^[a-zA-Z0-9]{1,10}$/,message: '1-10位英文名,可包含数字',trigger: ['blur','change']}],
      },
      loading0: false,
      loading1: false,
      picture:'', //背景图片
      list:[],
      //对话框
      visible: false,
      loading:false,
      dialogForm:{
        picture:''
      },
      dialogRules:{
        picture:{required: true,message: '不能为空',trigger: ['change','blur']}
      },


      exSize: 2,
      fileEx: 'JPG | JPEG | PNG',
      width: 300,
      height:150,
      uploadAction: 'http://106.54.165.67:8080/file/upload', // 上传URL
      header: {'token': localStorage.getItem('token')}, // 设置上传头部
      imageUrl: '', // 预览图片Url
      progessCount: 0, // 上传进度
      fileExArrs: ['jpg' ,'jpeg','png']

    },
    methods: {
      /** 提交 */
      submit(code) {
        console.log(code)
        if(code == 6 || code == 7 || code == 8){
          const params = {
            code: code
          }
          _axios.post('/generate-name', params).then(res=>{
            if(res.code === 200){
              this.form[`name${code}`] =  res.data.value
              this.copy(code)
            }else{
              this.$message({
                message: res.msg || '请求失败',
                type: 'error'
              });
            }
          })
        }else{
          const params = {
            code: code,
            nickName: this.form[`name${code}`]
          }
          this.$refs.form.validateField(`name${code}`,
          (valid) =>{
            if(valid){return false;}
            else{
              _axios.post('/generate-name', params).then(res=>{
                this.loading1 = false;
                if(res.code === 200){
                  console.log(this.form)
                  if(code == 5){
                    // this.form[`name${code}`]  =  res.data.map((item)=> item.value);
                    this.list = res.data
                  }else{
                    this.form[`name${code}`]  =  res.data.value
                    this.copy(code)
                  }
                }else{
                  this.$message({
                    message: res.msg || '请求失败',
                    type: 'error'
                  });
                }
              })
            }
          }
          )
        }

      },
      /**复制*/
      copy(code){
        // if(type == 0){
          if(this.form[`name${code}`]){
            let textarea = document.createElement("input");//创建input元素
            const currentFocus = document.activeElement;//当前获得焦点的元素，保存一下
            document.body.appendChild(textarea);//添加元素
            textarea.value = this.form[`name${code}`]  ;
            textarea.focus();

            textarea.setSelectionRange(0, textarea.value.length);//获取光标起始位置到结束位置
            //textarea.select(); 这个是直接选中所有的，效果和上面一样
            try {
              var flag = document.execCommand("copy");//执行复制
              if(flag)
                this.$message({message: '已自动复制到剪贴板', type: 'success'})
            } catch(eo) {
              var flag = false;
            }
            document.body.removeChild(textarea);//删除元素
            currentFocus.focus(); //恢复焦点
            this.$set(this.form,`name${code}` ,'')
          }else{
            return
          }
        // }else{
        //   if(this.form.name1 && this.form.name1.length > 0) {
        //     const Url1 = document.getElementById("copy1");
        //     Url1.select(); // 选择对象
        //     console.log(Url1,Url1.select())
        //     document.execCommand("Copy"); // 执行浏览器复制命令
        //     this.$message({message: '已自动复制到剪贴板', type: 'success'})
        //     this.$set(this.form,'name1','')
        //   }else{
        //     return
        //   }
        // }

      },
      /**打开对话框*/
      openDialog(){
        this.dialogForm.picture = localStorage.getItem('picture');
        console.log(2,this.dialogForm)
        this.imageUrl = this.picture
        this.visible = true
      },

      /**提交对话框*/
      dialogSubmit(){
        this.$refs.dialogForm.validate(valid => {
          if (valid) {
            this.loading = true;
            _axios.post(`/background`,{shortName:this.dialogForm.picture}).then(res => {
              if (res.code === 200) {
                this.$message({message:'更新成功',type:'success'})
                this.getImage()
                this.loading = false;
                this.visible = false;
              }else{
                this.$message({
                  message: res.msg || '请求失败',
                  type: 'error'
                });
                this.loading = false;
                this.visible = false;
              }
            });

          }
        })
      },
      /**退出登录*/
      logOut(){
        _axios.get(`/logout`).then(res => {
          if (res.code === 200) {
            localStorage.clear()
            window.location.href = './login.html'
          }else{
            this.$message({
              message: res.msg || '请求失败',
              type: 'error'
            });
          }
        });
      },
      /**获取背景图片*/
      getImage(type){
        _axios.get('/load').then(res => {
          if(res.code === 200){
            this.picture = res.data.shortName ? `http://106.54.165.67:8080${res.data.shortName}` : '../mum.jpg'
            localStorage.setItem('picture', res.data.shortName); // sessionStorage.setItem(TokenKey, token) 本地存储token
          }else{
            this.$message({
              message: res.msg || '请求失败',
              type: 'error'
            });
          }
        })
      },


      /** 文件选择的回调 */
      handleBeforeUpload(file) {
        //验证图片格式 大小
        const fileExarr = file.name.split('.');
        const fileExStr = fileExarr[fileExarr.length - 1].toLowerCase(); // 将后缀转为小写
        const isFileSize = file.size / 1024 / 1024 < this.exSize;
        if (this.fileExArrs.indexOf(fileExStr) === -1) {
          this.$message({
            message: `图片只能是 ${this.fileEx} 格式!`,
            type: 'warning'
          });
          return false;
        }
        if (!isFileSize) {
          this.$message({
            message: `图片大小不能超过 ${this.exSize} MB!`,
            type: 'warning'
          });
          return false;
        }
      },
      /** 上传中的进度回调 */
      handleUploadProgress(event) {
        this.progessCount = Math.floor(event.percent);
      },
      /** 上传成功的回调 */
      handleUploadSuccess(res) {
        if (res.code == 200) {
          this.progessCount = 0;
          this.imageUrl = `http://106.54.165.67:8080${res.data}`;
          this.dialogForm = { //上传得值
            picture: res.data
          }
          console.log(1,this.dialogForm)
        } else {
          this.$message({
            message: res.msg || '图片上传失败,请选择重新上传',
            type: 'error'
          });
        }
      },
      /** 上传失败的回调 */
      handleUploadError() {
        this.progessCount = 0;
        this.$message({
          message: res.msg || '图片上传失败,请选择重新上传',
          type: 'error'
        });
      },
    },
    created() {
      if(!localStorage.getItem('token')){
        window.location.href = './login.html'
      }
      this.getImage()
    }
  })
</script>
</body>
</html>
